<template>
    <!-- 需要和gridList组件通信  给该组件传入数据 (被选中的分类) -->
    <van-sidebar v-model="activeCategory" @change="onChange">
        <van-sidebar-item v-for="item, index in categoryList" :key="index" :title="(item as unknown as string)" />
    </van-sidebar>
</template>

<script setup lang="ts">
import type { Ref } from 'vue';
import { ref, reactive, computed, onMounted, watchEffect } from 'vue';
import { getCategoryListAPI, getBrandListAPI } from "@/api/product";
import { useSlots,useAttrs } from 'vue';

import RenderContent from "@/components/RenderContent.vue"

// 组合式语法中如何接收父组件传入的数据 (属性/方法)  自定义事件()  v-model(传入的数据)

// let props = defineProps(["a", "b"]);  // 接收父组件传入的数据(props)
let emits = defineEmits(["update:modelValue"]);  // 接收父组件传入的自定义事件
let module = defineModel("modelValue"); // 接收父组件传入的数据(以v-model:aaa="aaa");

console.log(111, module);



// 可以以选项式写法定义组件配置项
defineOptions({
    name:"xxx",
    inheritAttrs:false,
})


let activeCategory = ref(0);  // sidebar 活跃状态的下标 
let categoryList = ref([]);


const onChange = (index:number)=>{
    activeCategory.value  = index;
    emits("update:modelValue", (categoryList.value[index] as any));
}

const getActiveCategory = ()=>{
    console.log("组件内暴露方法测试,父组件可以通过ref名获取当前组件,调用方法");
    return  activeCategory.value;
}


const getCategoryList = async () => {
    try {
        let result = await getCategoryListAPI();
        console.log("分类列表请求成功", result);
        categoryList.value = result.data;

    } catch (err: any) {
        // showFailToast(err.message);
    }
}


// defineExpose(); //当前组件 向外暴露的方法  可以先通过ref获取组件, 在通过组件实例使用  this.$refs.xxx.方法名()
defineExpose({
    getActiveCategory,
    categoryList,
});

onMounted(async () => {
    await getCategoryList();  // 等分类列表请求成功

    if(module.value == null){
        activeCategory.value = 0;
        emits("update:modelValue", (categoryList.value[0] as any));
    }else{
        var index = categoryList.value.indexOf(module.value as never);

        if(index != -1){
            activeCategory.value  = index;
        }else{
            activeCategory.value = 0;
            emits("update:modelValue", (categoryList.value[0] as any).trim());
        }
    }
    
})

</script>

<style scoped></style>